<template>
  <div class="app-container">
    <slot name="header" />
    <div class="my-5">
      <slot name="btns" />
    </div>

    <el-table :height="height" :data="tableList.data" border v-loading="loading" ref="table">
      <template v-for="(item, i) in props.columns">
        <slot v-if="item.slot" :name="item.slotName" :key="i" />
        <el-table-column v-if="!item.slot" v-bind="item" :key="i" />
      </template>
    </el-table>
    <el-pagination
      class="mt-2 float-right"
      background
      :layout="props.layout"
      :page-sizes="props.pageSizes"
      :total="total"
      :page-size="pageSize"
      :currentPage="currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, Ref, onMounted, nextTick } from "vue"
import type { TableInstance } from "element-plus"
import type { columnsType } from "./types/index"
const props = defineProps({
  columns: {
    type: Array as () => columnsType[],
    default: () => []
  },
  fetch: {
    type: Function,
    required: true
  },
  layout: {
    type: String,
    default: " total, prev, pager, next"
  },
  pageSizes: {
    type: Array as () => number[],
    default: () => [10, 20, 50, 100]
  },
  pageSize: {
    type: Number,
    default: 10
  },
  currentPage: {
    type: Number,
    default: 1
  }
})
const tableList = reactive({ data: [] })
const table: Ref<TableInstance | null> = ref(null)
const total = ref(0)
const height = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const handleSizeChange = () => {}
const handleCurrentChange = () => {}
interface tableParams {
  currentPage: number
  pageSize: number
}
const params: tableParams = {
  currentPage: currentPage.value,
  pageSize: pageSize.value
}
const load = async () => {
  loading.value = true
  const data = await props.fetch(params)
  tableList.data = data.data
  total.value = data.total
  loading.value = false
}
onMounted(() => {
  updataHeight()
  window.addEventListener("resize", updataHeight)
})
const updataHeight = () => {
  console.log("resize")
  nextTick(() => {
    const $el = table.value && table.value.$el
    let h = 0
    const indexs = [0, 1, 3]

    indexs.forEach((index) => {
      h += $el.parentNode.children[index].offsetHeight
    })
    height.value = $el.parentNode?.offsetHeight - h - 65
    console.log(height.value, "height")
  })
}
defineExpose({ load, updataHeight })
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 90px);
  overflow: scroll;
}
</style>
